package com.example.scaffold_demo.base;

import android.os.Bundle;
import android.widget.Toast;


import com.example.httplibrary.mvp.BaseView;
import com.example.httplibrary.mvp.proxy.ActivityMvpProxy;
import com.example.httplibrary.mvp.proxy.ActivityMvpProxyImpl;
import com.example.scaffold_demo.widget.eventbus.EventBean;
import com.example.scaffold_demo.widget.eventbus.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Author: 李巷阳
 * Date: 2020/6/6
 * Part:基类的 Model
 * Description:
 */
public abstract class BaseActivity extends AppCompatActivity implements BaseView {
    private ActivityMvpProxy mMvpProxy;
    private Unbinder mUnbinder;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setLayout());
        mUnbinder = ButterKnife.bind(this);
        if (isRegisterEventBus()) {
            EventBusUtil.register(this);
        }
        // 创建 Mvp 的代理
        mMvpProxy = createMvpProxy();
        initTitle();
        initData();
        initView();
    }
    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }


    protected abstract void initTitle();

    /**
     * 创建 Mvp 的代理  自己去写 Fragment
     * @return
     */
    private ActivityMvpProxy createMvpProxy() {
        if(mMvpProxy == null){
            mMvpProxy = new ActivityMvpProxyImpl<>(this);
        }
        // 创建preserter,并把activity生命周期绑定至presenter
        mMvpProxy.bindAndCreatePresenter(this);
        return mMvpProxy;
    }


    protected abstract int setLayout();

    protected abstract void initData();

    protected abstract void initView();


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(EventBean event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onStickyEventBusCome(EventBean event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(EventBean event) {

    }
    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(EventBean event) {

    }
    @Override
    public void showLoading() {
        Toast.makeText(this, "加载loading", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void dismissLoading() {
        Toast.makeText(this, "关闭loading", Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();

    }
}
